//
//  HJHomeViewModel.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/27.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class HJHomeViewModel: NSObject {


    //创建视图控制器,视图控制器引用ViewModel
    var viewModelArray : [HJStatusViewModel] = [HJStatusViewModel]()
    
    func loadData(isPullUp : Bool , finished: @escaping (Bool,Int) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var parameters = ["access_token" : HJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token ?? ""]
        
        //上拉加载跟多数据需要添加参数Max_id
       //判断是否是第一次刷新数据
        if isPullUp {
            //上拉操作
            let id = viewModelArray.last?.status?.id ?? 0
            parameters["max_id"] = "\(id - 1)"
        }else {
            //第一次加载数据
            let id = viewModelArray.last?.status?.id ?? 0
            parameters["max_id"] = "\(id)"
        }
        
        
        //网络请求数据
        HJNetworkTools.sharedTool.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            if error != nil {
                finished(false,0)
                return
            }
            //解析数据
            //将数据转换为字典数据
            let dict = responseObject as! [String:Any]
            
            
            //从字典中取值,根据"statuses"来获取数据
            guard let array = dict["statuses"] as? [[String : Any]] else{
                finished(false,0)
                return
            }
            
            /*
             MVC模式下使用这种方式转换
            let tempArray = NSArray.yy_modelArray(with: HJStatus.self, json: array) as! [HJStatus]
            self.statuses = tempArray
            
            */
           // print(array)
            
            var tempArray = [HJStatusViewModel]()
            for item in array {
                
                let viewModel = HJStatusViewModel()
                let s = HJStatus()
                s.yy_modelSet(with: item)
                viewModel.status = s
                tempArray.append(viewModel)

            }
            //判断是上拉刷新还是下拉刷新,如果是上拉刷新则拼接在数组后面,下拉刷新拼接在前面
           
            if isPullUp {
                self.viewModelArray = self.viewModelArray + tempArray
            }else {
                self.viewModelArray = tempArray + self.viewModelArray
            }
            
            //finished(true ,tempArray.count)
            
            self.cacheSingleImage(dataArray: tempArray, cacheImageFinished: finished)
        }
    }
    
    //下载单张图片
    private func cacheSingleImage(dataArray: [HJStatusViewModel] , cacheImageFinished:@escaping (Bool,Int) -> ()) {
        
        //使用调度组把单张图片全部下载完成
        let group = DispatchGroup.init()
        //遍历数组判断单张图片
        for viewModel in dataArray {
            if viewModel.pictureInfos?.count == 1 {
                //获取下载地址
                let url = URL(string: viewModel.pictureInfos?.first?.wap_pic ?? "")
            //在开始异步任务之前 就应该入组  调度组中的异步任务 + 1
                group.enter()
                
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                    
                    //到这里图片下载完毕
                    print("单张图片下载完成")
                    group.leave()
                })
            }
        }
        group.notify(queue: DispatchQueue.main) {
            //下载完毕执行回调
               print("所有的单张图片下载完毕")
            cacheImageFinished(true,dataArray.count)
        }
    }
    
    
}










